package rest

import (
	"encoding/json"
	"net/http"
)

type Result struct {
	Success bool        `json:"success"`
	Data    interface{} `json:"data,omitempty"`
	Msg     string      `json:"msg,omitempty"`
	Total   int         `json:"total,omitempty"`
}

func RenderData(w http.ResponseWriter, data interface{}, err error) {
	if err != nil {
		RenderErr(w, err)
	} else {
		RenderJSON(w, data)
	}
}
func RenderJSONTotal(w http.ResponseWriter, data interface{}, total int) {
	w.Header().Set("Content-Type", "application/json")
	_ = json.NewEncoder(w).Encode(&Result{
		Success: true,
		Data:    data,
		Total:   total,
	})
}
func RenderJSON(w http.ResponseWriter, data interface{}) {
	RenderJSONTotal(w, data, 0)
}
func RenderErr(w http.ResponseWriter, e error) {
	w.Header().Set("Content-Type", "application/json")
	_ = json.NewEncoder(w).Encode(&Result{
		Success: false,
		Msg:     e.Error(),
	})
}
